package cn.platform.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.platform.response.AResponse;
import cn.platform.response.Result;
import cn.platform.util.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("程序出错啦",e);
        return Result.error("出错啦，请联系管理员");
    }


    @ExceptionHandler
    public Result handleBizException(BusinessException e){
        log.error("程序出错啦",e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<?> handleNotLoginException(NotLoginException ex, WebRequest request) {
        log.warn(ex.getMessage());
        AResponse res = AResponse.error(ErrorCode.INVALID_TOKEN, "未登录");
        return new ResponseEntity<>(res, HttpStatus.OK);
    }

    @ExceptionHandler(NotPermissionException.class)
    public ResponseEntity<?> handleException(NotPermissionException ex, WebRequest request) {
        log.warn(ex.getMessage());
        AResponse res = AResponse.error(ErrorCode.UNAUTHORIZED, "未授权");
        return new ResponseEntity<>(res, HttpStatus.OK);
    }

    @ExceptionHandler
    public Result duplicateException(DuplicateKeyException e){
        log.error("程序出错啦~",e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String duplicateKey = errMsg.split("'")[1];
        return Result.error(duplicateKey+"已存在");
    }

}
